import React, {Component} from 'react'
import PropTypes from 'react-router/lib/PropTypes'

import WeaMonthPicker from '../wea-month-picker/'

import './index.less'

class WeaDateSwitch extends Component {
    constructor(props) {
        super(props)
        let value = props.defaultValue || new Date()
        this.state = {
            value: value,
            disabled: this.disabledDate(this.getNextMonth(value))
        }
    }

    render() {
        let {title, style} = this.props,
            {value, disabled} = this.state
        return (
            <div className="wea-date-switch" style={style}>
                <span className="wea-ds-pre icon-coms-Browse-box-delete" onClick={this.preDateClick}/>
                <WeaMonthPicker value={value} onChange={this.onChange} disabledDate={this.disabledDate}/>
                {title ? <span className="wea-ds-title">{title}</span> : ""}
                {
                    <span className={`wea-ds-next icon-coms-Browse-box-Add-to ${disabled ? 'disabled' : ''}`} onClick={disabled ? '': this.nextDateClick}/>
                }
            </div>
        )
    }

    preDateClick = () => {
        let {value} = this.state
        value.setMonth(value.getMonth() - 1);
        this.onChange(value);
    }

    nextDateClick = () => {
        let {value} = this.state
        value.setMonth(value.getMonth() + 1)
        this.onChange(value);
    }

    onChange = (value) => {
        this.setValue(value);
        if (this.props.onChange) this.props.onChange(value);
    }
    
    setValue = (value) => {
        let nextMonth = this.getNextMonth(value);
        this.setState({value: value, disabled: this.disabledDate(nextMonth)})
    }
    getNextMonth = (value) => {
        let nextMonth = new Date(value.getTime());
        nextMonth.setMonth(nextMonth.getMonth() + 1);
        return nextMonth;
    }
    
    disabledDate = (current) => {
        let year = current.getFullYear(),
            month = current.getMonth(),
            date = new Date(),
            _year = date.getFullYear(),
            _month = date.getMonth()
        
        return (year * 100 + month * 1) > (_year * 100 + _month * 1)
    }
}

export default WeaDateSwitch